//
//  ServerConfigViewController.m
//  Auction
//
//  Created by Gary on 15/9/11.
//  Copyright (c) 2015年 Lebo. All rights reserved.
//

#import "ServerConfigViewController.h"
#import "Common.h"
#import "DTCoreText.h"

static const NSString *kRunEnvTipTest = @"<span style=\"text-align: right; line-height: 100%; font-size: 11px; color: #28FF28\">认证支付金额为<span style=\"font-size: 13px; color: blue\">0.01</span>元<br>QPos刷卡金额为<span style=\"font-size: 13px; color: blue\">0.1</span>元</span>";
static const NSString *kRunEnvTipProduction = @"<span style=\"text-align: right; line-height: 100%; font-size: 11px; color: #28FF28\">认证支付金额为<span style=\"font-size: 13px; color: red\">价格全额</span><br>QPos刷卡金额为<span style=\"font-size: 13px; color: red\">价格全额</span></span>";
static const NSString *kPayEnvTipTest = @"<span style=\"text-align: right; line-height: 100%; font-size: 11px; color: #28FF28\">连接认证支付和QPos的<span style=\"font-size: 13px; color: blue\">测试</span>环境<br>连连支付交易物品类型为<span style=\"font-size: 13px; color: blue\">虚拟</span><br>QPos开发ID为<span style=\"font-size: 13px; color: blue\">测试</span>账号</span>";
static const NSString *kPayEnvTipProduction = @"<span style=\"text-align: right; line-height: 100%; font-size: 11px; color: #28FF28\">连接认证支付和QPos的<span style=\"font-size: 13px; color:red\">生产</span>环境<br>连连支付交易物品类型为<span style=\"font-size: 13px; color:red\">实物</span><br>QPos开发ID为<span style=\"font-size: 13px; color: red\">正式</span>账号</span>";

@interface ServerConfigViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *configView;
@property (weak, nonatomic) IBOutlet UIView *runEnvView;

@property (weak, nonatomic) IBOutlet UISegmentedControl *runEnvSlider;
@property (weak, nonatomic) IBOutlet DTAttributedLabel *runEnvTip;
@property (weak, nonatomic) IBOutlet UITextField *urlTextField;
@property (weak, nonatomic) IBOutlet UITextField *portTextField;
@property (weak, nonatomic) IBOutlet UITextField *apiTextField;
@property (weak, nonatomic) IBOutlet UISegmentedControl *payEnvSlider;
@property (weak, nonatomic) IBOutlet DTAttributedLabel *payEnvTip;

@end

@implementation ServerConfigViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self defaultNavigationLeftBar];
    
    [_runEnvSlider setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor darkGrayColor]}
                                 forState:UIControlStateNormal];
    [_runEnvSlider setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}
                                 forState:UIControlStateSelected];
    [_payEnvSlider setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor darkGrayColor]}
                                 forState:UIControlStateNormal];
    [_payEnvSlider setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}
                                 forState:UIControlStateSelected];
    _runEnvSlider.selectedSegmentIndex = ![Common isProductionEnv] ? 0 : 1;
    _payEnvSlider.selectedSegmentIndex = ![Common isPaymentProductionEnv] ? 0 : 1;
    [self setPaymentEnvViews:[Common isPaymentProductionEnv]];
    [self setRunningEnvViews:[Common isProductionEnv]];
    
    //初始化控件
    //NSString *baseServerURL = [Common baseServerURL];
    NSString *baseServerURL = [[NSUserDefaults standardUserDefaults] objectForKey:kUSKeyBaseServerURL];
    if (!baseServerURL) {
        baseServerURL = (NSString *)kBaseServerURL;
    }
    NSArray *components = [baseServerURL componentsSeparatedByString:@"/"];
    if (components.count >= 3) {
        NSString *urlAndPort = components[2];
        NSArray *urlComponents = [urlAndPort componentsSeparatedByString:@":"];
        _urlTextField.text = urlComponents[0];
        if (urlComponents.count >= 2) {
            _portTextField.text = urlComponents[1];
        }
        
        if (components.count >= 4) {
            NSMutableString *api = [NSMutableString stringWithString:components[3]];
            for (int i = 4; i < components.count; i++) {
                [api appendFormat:@"/%@", components[i]];
            }
            _apiTextField.text = api;
        }
    }
    
    //添加滑动手势
    UISwipeGestureRecognizer *gr = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                             action:@selector(handleViewSwipe:)];
    gr.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:gr];
    self.view.userInteractionEnabled = YES;
    
    //背景渐变
    CAGradientLayer *gradientLayer;
    UIView *layerView = [[UIView alloc] initWithFrame:_configView.bounds];
    
    gradientLayer = [CAGradientLayer layer];  // 设置渐变效果
    gradientLayer.bounds = layerView.bounds;
    gradientLayer.borderWidth = 0;
    
    gradientLayer.frame = layerView.bounds;
    gradientLayer.colors = [NSArray arrayWithObjects:
                            (id)[[UIColor colorWithWhite:0.4f alpha:1.f] CGColor],
                            (id)[[UIColor colorWithWhite:0.6f alpha:1.f] CGColor],
                            (id)[[UIColor colorWithWhite:0.8f alpha:1.f] CGColor],
                            (id)[[UIColor colorWithWhite:0.6f alpha:1.f] CGColor],
                            (id)[[UIColor colorWithWhite:0.4f alpha:1.f] CGColor],
                            nil];
    //gradientLayer.startPoint = CGPointMake(0.5, 0.5);
    //gradientLayer.endPoint = CGPointMake(0.5, 1.0);
    
    [layerView.layer insertSublayer:gradientLayer atIndex:0];
    
    [_configView insertSubview:layerView belowSubview:_runEnvView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 业务处理

- (BOOL)checkConfigValue {
    BOOL ret = [self checkUrl];
    if (!ret) {
        [Common showAlert:@"网址瞎填的吧！" message:nil];
        return NO;
    }
    
    ret = [self checkPort];
    if (!ret) {
        [Common showAlert:@"端口瞎填的吧！" message:nil];
        return NO;
    }
    
    ret = [self checkAPI];
    if (!ret) {
        [Common showAlert:@"API瞎填的吧！" message:nil];
        return NO;
    }
    
    return YES;
}

- (BOOL)checkUrl {
    NSString *url = _urlTextField.text;
    if ([Common regexString:url match:@"^((([1-9]?|1\\d)\\d|2([0-4]\\d|5[0-5]))\\.){3}(([1-9]?|1\\d)\\d|2([0-4]\\d|5[0-5]))$"]) {
        return YES;
    };
    
    if ([Common regexString:url match:@"^[a-zA-Z\\d]+\\.[a-zA-Z\\d]+[a-zA-Z\\d\\.]*[a-zA-Z\\d]+$"]) {
        return YES;
    }
    
    return NO;
}

- (BOOL)checkPort {
    NSString *port = _portTextField.text;
    if ([Common isEmptyString:port]) {
        return YES;
    }
    
    if ([Common regexString:port match:@"^[1-9][0-9]+$"]) {
        if ([port intValue] <= 65535) {
            return YES;
        }
    }
    
    return NO;
}

- (BOOL)checkAPI {
    NSString *api = _portTextField.text;
    if ([Common isEmptyString:api]) {
        return YES;
    }
    
    if ([Common regexString:api match:@"^([\\w\\-\\.?&=+]+[/]?)+[^/]$"]) {
        return YES;
    }
    
    return NO;
}

- (void)setRunningEnvViews:(BOOL)isProEnv {
    if (isProEnv) {
        _runEnvTip.attributedString = [Common attrStrFromHtmlText:(NSString *)kRunEnvTipProduction];
        _urlTextField.enabled = NO;
        _portTextField.enabled = NO;
        _apiTextField.enabled = NO;
        _urlTextField.backgroundColor = [UIColor lightGrayColor];
        _portTextField.backgroundColor = [UIColor lightGrayColor];
        _apiTextField.backgroundColor = [UIColor lightGrayColor];
        
        _payEnvSlider.selectedSegmentIndex = 1;
        _payEnvSlider.enabled = NO;
        _payEnvSlider.backgroundColor = [UIColor lightGrayColor];
        [self setPaymentEnvViews:YES];
    } else {
        _runEnvTip.attributedString = [Common attrStrFromHtmlText:(NSString *)kRunEnvTipTest];
        _urlTextField.enabled = YES;
        _portTextField.enabled = YES;
        _apiTextField.enabled = YES;
        _urlTextField.backgroundColor = [UIColor whiteColor];
        _portTextField.backgroundColor = [UIColor whiteColor];
        _apiTextField.backgroundColor = [UIColor whiteColor];
        _payEnvSlider.enabled = YES;
        _payEnvSlider.backgroundColor = [UIColor clearColor];
    }
}

- (void)setPaymentEnvViews:(BOOL)isProEnv {
    const NSString *text = !isProEnv ? kPayEnvTipTest : kPayEnvTipProduction;
    _payEnvTip.attributedString = [Common attrStrFromHtmlText:(NSString *)text];
}

#pragma mark - 事件响应

- (void)pageBack {
    [_urlTextField resignFirstResponder];
    [_portTextField resignFirstResponder];
    [_apiTextField resignFirstResponder];
    
    if ([self checkConfigValue]) {
        NSString *port = [Common trim:_portTextField.text];
        if ([Common isEmptyString:port]) {
            port = @"";
        } else {
            port = [NSString stringWithFormat:@":%@", port];
        }
        
        NSString *api = [Common trim:_apiTextField.text];
        if ([Common isEmptyString:api]) {
            api = @"";
        } else {
            api = [NSString stringWithFormat:@"/%@", api];
        }
        
        NSString *url = [NSString stringWithFormat:@"%@%@%@", [[Common trim:_urlTextField.text] lowercaseString], port, api];
        NSString *baseServerURL;
        if ([Common regexString:url match:@"^http[s]?://.*$"]) {
            baseServerURL = url;
        } else {
            baseServerURL = [NSString stringWithFormat:@"http://%@", url];
        }
        if (![Common isProductionEnv]) {
            [Common updateBaseServerURL:baseServerURL save:YES];
        } else {
            [[NSUserDefaults standardUserDefaults] setObject:baseServerURL forKey:baseServerURL];
        }
        self.navigationController.navigationBarHidden = YES;
        [super pageBack];
    }
}

- (void)handleViewSwipe:(UISwipeGestureRecognizer*)gr {
    if(gr.direction==UISwipeGestureRecognizerDirectionRight) {
        [self pageBack];
    }
}

- (IBAction)changeRunEnv:(id)sender {
    BOOL isProEnv = _runEnvSlider.selectedSegmentIndex == 1;
    [self setRunningEnvViews:isProEnv];
    [Common updateProductionEnv:isProEnv];
    if (isProEnv) {
        [Common updateBaseServerURL:(NSString *)kBaseServerURLProduction save:NO];
        [self setPaymentEnvViews:isProEnv];
        [Common updatePaymentProductionEnv:isProEnv];
    }
}

- (IBAction)changePayEnv:(id)sender {
    BOOL isProEnv = _payEnvSlider.selectedSegmentIndex == 1;
    [self setPaymentEnvViews:isProEnv];
    [Common updatePaymentProductionEnv:isProEnv];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _urlTextField) {
        [_portTextField becomeFirstResponder];
    } else if (textField == _portTextField) {
        [_apiTextField becomeFirstResponder];
    } else {
        [textField resignFirstResponder];
    }
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == _urlTextField) {
        if ([kBaseServerURLProduction isEqualToString:[Common trim:_urlTextField.text]]) {
            _runEnvSlider.selectedSegmentIndex = 1;
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
